﻿using System.Web.Mvc;
using ZSoftInstagram.Domain.Board;
using ZSoftInstagram.Services.Abstraction;
using ZSoftInstagram.UI.ViewModels;
using ZSoftInstagram.UI.Web.Infrastructure.AppEvents.BaseControllers;
using ZSoftInstagram.UI.Web.Infrastructure.Filters;
using Microsoft.AspNet.Identity;
using System.Threading.Tasks;
using System.Linq;
using System;

namespace ZSoftInstagram.UI.Web.Controllers
{
    public class PinBoardController : EntityController<ImagePinBoard>
    {
        private IPinBoardService _service;

        protected override IEntityService<ImagePinBoard> Service
        {
            get
            {
                return _service;
            }
        }

        public PinBoardController(IPinBoardService service)
        {
            this._service = service;
        }
        
        [AjaxOnly, Authorize]
        public ActionResult UserBoards()
        {
            var model = _service.GetUserBoardsAsync(User.Identity.GetUserId<int>()).Result;
            
            return View(model.OrderByDescending(m => m.Date).ToList());
        }
        
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Details(int id)
        {
            return View();
        }
        
        [AjaxOnly, Authorize]
        public ActionResult Create()
        {
            var model = this._service.GetCreateModel();
            return View(model);
        }
        
        [AjaxOnly, HttpPost, ValidateModel, Authorize]
        public async Task<ActionResult> Create(PinBoardCreateModel model)
        {
            try
            {
                model.UserId = User.Identity.GetUserId<int>();
                return (await _service.CreateAsync(model)).ToDbServiceResult();
            }
            catch
            {
                return View();
            }
        }

        [HttpGet, AjaxOnly]
        public async Task<ActionResult> Edit(int id)
        {
            return View(await this._service.GetBoardAsync(id));
        }

        // POST: PinBoard/Edit/5
        [HttpPost]
        public ActionResult Edit(PinBoardEditModel model)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: PinBoard/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: PinBoard/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, PinBoardDeleteModel model)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
